package com.gosling.cloudspace.aop;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import org.slf4j.MDC;
import org.springframework.core.task.TaskDecorator;

import java.util.Map;

/**
 * 重写线程任务装饰者，设置MDC的traceId
 * @author lihonglin
 * @date 2022/12/22 14:42
 */
public class MdcTaskDecorator implements TaskDecorator {
    private static String TRADE_ID = "traceId";

    @Override
    public Runnable decorate(Runnable runnable) {
        Map<String, String> map = MDC.getCopyOfContextMap();
        return () -> {
            try {
                MDC.setContextMap(map);
                String traceId = MDC.get(TRADE_ID);
                if(StrUtil.isEmpty(traceId)) {
                    traceId = IdUtil.fastUUID();
                    MDC.put(TRADE_ID, traceId);
                }
                runnable.run();
            }finally {
                MDC.clear();
            }
        };
    }
}
